package com.kevinkk.array;

/**
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 *
 * 和 SpiralMatrix 一样，同样是用四个指针模拟旋转过程
 */

public class SpiralMatrixII {
    class Solution {
        public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            int count = 1;
            int up = 0, right = n - 1, down = n - 1, left = 0;

            while (true) {
                for (int i = left; i <= right; i++, count++)
                    res[up][i] = count;
                if (++up > down)
                    break;

                for (int i = up; i <= down; i++, count++)
                    res[i][right] = count;
                if (--right < left)
                    break;

                for (int i = right; i >= left; i--, count++)
                    res[down][i] = count;
                if (--down < up)
                    break;

                for (int i = down; i >= up; i--, count++)
                    res[i][left] = count;
                if (++left > right)
                    break;
            }
            return res;
        }
    }
}
